package htdi.act.usrmgr.endpoints;

import act.app.ActionContext;
import act.crypto.AppCrypto;
import htdi.act.usrmgr.models.User;
import org.osgl.aaa.NoAuthentication;
import org.osgl.http.H;
import org.osgl.mvc.annotation.Action;
import org.osgl.mvc.annotation.PostAction;
import org.osgl.util.Token;

import javax.inject.Inject;
import javax.validation.constraints.NotNull;

/**
 * Services processing signUp, activate, login and logout,
 */
@NoAuthentication
public class SignService extends ServiceBase {

    @Inject
    private User.Dao userDao;

    @Inject
    private AppCrypto crypto;

    /**
     * Sign up an new user.
     *
     * @param user
     *      the user data
     */
    @PostAction("sign_up")
    public void signUp(User user) {
        userDao.signUp(user);
    }

    /**
     * Activate an account.
     *
     * @param tk
     *      the activate token (sent out by email)
     * @param password
     *      the initial password set by user
     */
    @PostAction("activate")
    public void activate(String tk, char[] password) {
        Token token = crypto.parseToken(tk);
        notFoundIfNot(token.isValid());
        token.consume();
        User user = userDao.findByUsername(token.id());
        notFoundIfNull(user);
        user.setPassword(password);
        userDao.save(user);
    }

    /**
     * Login a user by email and password.
     *
     * @param email
     *      the user's email.
     * @param password
     *      the user's password.
     */
    @PostAction("login")
    public void login(@NotNull String email, @NotNull char[] password, ActionContext context) {
        unauthorizedIfNot(userDao.authenticate(email, password));
        context.login(email);
    }

    /**
     * Logout a user.
     */
    @Action(value = "logout", methods = {H.Method.POST, H.Method.GET})
    public void logout(ActionContext context) {
        context.logout();
    }

}
